import { State } from "framework/FSM/AState";
import { ActionArgHelper } from "../../../ActionManager/ActionArgHelper";
import { EntityHelper } from "utils/entity/EntityHelper";
import { PositionHelper } from "utils/position/PositionHelper";
 

/**
 攻击任务
 */ 
export class AttackTask<T extends IStateArg<Creep>>  extends State<T>
{

    //
    public  getActions(arg:T):Action[]
    {
        
        const memory = arg.entity.getNodeMemory();
        if(!memory.taskid)
        {
            return [];
        }
        const task =arg.task as ITask<ITeamTaskData<"defend">>;
        if(!task)
        {
            // 查找不到任务
            return []
        }
        const creep = arg.entity;
    
       
        const trifc = creep.getTactic() as IAttackTactic;
        if(trifc  )
        {
            if(trifc.targets && trifc.targets.length>0)
            {
                const obj =  Game.getObjectById(trifc.targets[0].id!) as AttackObject
                if(obj)
                {
                    // creep.log(`info`,'移动到最近攻击目标',JSON.stringify(trifc.targets))
                    if(creep.bodyCount(ATTACK))
                    {
                        return [ActionArgHelper.actionAttack(creep,obj,"attackRed"),];
                    }
                    else
                    {
                        return [ActionArgHelper.actionAttack(creep,obj,"attackBlue")]
                    }
                }
               
            }
            else if(trifc.goal)
            {
                // creep.log(`info`,'移动到最近目标',JSON.stringify(trifc.goal))
                return [ActionArgHelper.actionMoveto(creep,trifc.goal,{}),];
            }
            else
            {
                creep.log(`info`,'没有进攻目标' );
            }
        }
         
        const workroom = Game.rooms[task.data.room];
        if(workroom && (task.data.arg.enemy || task.data.arg.structures))
        {   
            let target:Id<AttackObject>|undefined
            if(task.data.arg.enemy.length)
            {
                target =  task.data.arg.enemy[0];
            }
            else if(task.data.arg.structures.length)
            {
                target =  task.data.arg.structures[0];
            }
            if(target)
            {
                if(creep.bodyCount(ATTACK))
                {
                    return [ActionArgHelper.actionAttack(creep,Game.getObjectById(target) as AttackObject,"attackRed")];
                }
                else
                {
                    return [ActionArgHelper.actionAttack(creep,Game.getObjectById(target) as AttackObject,"attackBlue")]
                }
            }
            else 
            {
                creep.log(`warn`,'没有进攻目标' );
            }
        }
        return  [ ActionArgHelper.actionMoveto(creep,{pos:PositionHelper.Create({x:25,y:25,roomName:task.data.room}),range:10},{})]
    }
}
